package com.hq.common.scheduler;

import com.hq.common.utils.ApplicationContextUtils;
import com.hq.common.utils.TimeUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * Created by He Zhijie on 2015/7/19.
 */
public class SchedulerManager {
    private static final Logger logger = LoggerFactory.getLogger(SchedulerManager.class);
    private static Scheduler scheduler;

    public static void schedulerByCronExp(Job job, String cronExp, Map dataMap) {
    }

    public static void schedulerByCronExp(JobDetail job, String cronExp, Map dataMap, Date beginDate, Date endDate) {
    }

    /**
     * 创建simple trigger
     * @param jobClazz
     * @param triggerIdentity
     * @param triggerGroup
     * @param repeatCount
     * @param repeatInterval
     * @param dataMap
     * @param beginDate
     * @param endDate
     */
    public static void schedulerBySimple(Class jobClazz, String triggerIdentity, String triggerGroup, int repeatCount, long repeatInterval,
                                         Map dataMap, Date beginDate, Date endDate) {
        TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger().withIdentity(triggerIdentity, triggerGroup);
        if (beginDate != null) {
            triggerBuilder.startAt(beginDate);
        }
        if (endDate != null) {
            /*结束时间必须晚当前时间，并且开始时间必须早于结束时间*/
            if (endDate.before(TimeUtil.getDbCurrentDate()) || (beginDate != null && endDate.before(beginDate)))
                return;
            triggerBuilder.endAt(endDate);
        }
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInMilliseconds(repeatInterval).withRepeatCount(repeatCount);
        triggerBuilder.withSchedule(scheduleBuilder);
        triggerBuilder.forJob(jobClazz.getName());
        triggerBuilder.usingJobData(new JobDataMap(dataMap));
        try {
            getScheduler().scheduleJob(triggerBuilder.build());
        } catch (SchedulerException e) {
            logger.error("定时任务【{}】启动异常!", triggerIdentity);
        }
    }

    /**
     * 创建执行一次的触发器
     * @param jobClazz
     * @param triggerIdentity
     * @param triggerGroup
     * @param dataMap
     * @param beginDate
     * @param endDate
     */
    public static void schedulerByOnce(Class jobClazz, String triggerIdentity, String triggerGroup, Map dataMap, Date beginDate, Date endDate) {
        schedulerBySimple(jobClazz, triggerIdentity, triggerGroup, 0, 0, dataMap, beginDate, endDate);
    }

    private static Scheduler getScheduler() {
        if (scheduler == null) {
            scheduler = ApplicationContextUtils.getBean(Scheduler.class);
        }
        return scheduler;
    }

    public static void addJobs() {
        Collection<Job> jobList = ApplicationContextUtils.getBeanListOfType(Job.class);
        for (Job job : jobList) {
            JobBuilder jobBuilder = JobBuilder.newJob(job.getClass()).withIdentity(job.getClass().getName()).storeDurably(true);
            JobDetail jobDetail = jobBuilder.build();
            try {
                getScheduler().addJob(jobDetail, true);
            } catch (SchedulerException e) {
                logger.error("添加job异常", e);
            }
        }
    }

    /**
     * 卸载触发器
     * @param triggerId
     * @param triggerGroup
     * @return
     */
    public static boolean unscheduleJobByTrigger(String triggerId,String triggerGroup) {
        boolean result = Boolean.FALSE;
        try {
            return getScheduler().unscheduleJob(new TriggerKey(triggerId,triggerGroup));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return result;
    }
}
